package com.dbq.fast.common.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.StringReader;
import java.util.ArrayList;
/*
Gson解析null替换为空字符串
Gson gson =new Gson(); no
Gson gson = new GsonBuilder().serializeNulls().create();no
Gson gson =new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create(); yes

本地字段 没有对应时 字段为"null"
 */

public class GsonT {

    private static Gson mGson = null;

    public static <T> ArrayList<T> fromJsonList(String json, Class<T> cls) {
        if (mGson == null) {

            mGson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();

        }
        ArrayList<T> mList = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            mList.add(mGson.fromJson(elem, cls));
        }
        return mList;
    }

    public static <T> T parseJson(String json, Class<T> t) {
        if (mGson == null) {
            mGson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        }
        JsonReader reader = new JsonReader(new StringReader(json));
        reader.setLenient(true);
        T cT = mGson.fromJson(reader, t);
        return cT;
    }

    public static String toJson(Object obj) {
        if (mGson == null) {
            mGson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        }
        return mGson.toJson(obj);
    }

}